home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 14999 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.0 KB

  1. Path: news.gwdg.de!amuelle3
  2. From: amuelle3@gwdu19.gwdg.de (Arne Mueller )
  3. Newsgroups: comp.lang.c
  4. Subject: how to prevent overflow in unsigned?
  5. Date: 16 Apr 1996 16:35:55 GMT
  6. Organization: GWDG, Goettingen
  7. Message-ID: <4l0i9b$efq@gwdu19.gwdg.de>
  8. NNTP-Posting-Host: gwdu08-fddi.gwdg.de
  9. X-Newsreader: TIN [version 1.1 PL8]
  10.  
  11. Hello,
  12.  
  13. I've the following problem:
  14.  
  15. I have to write a function (I'm not allowed to use the standard functions of stdlib!)
  16. that reads an unsigned int from stdin (using getchar). 
  17.  
  18.  
  19.  
  20. My question: How to recognize an overflowWh 
  21. If the number is bigger than UINT_MAX, the variable that saves the number
  22. is not set to zero.
  23.  
  24. some code ... :
  25.  
  26. IO_STATUS unsigned_read(unsigned int *i)
  27. {
  28.   
  29.   int c;
  30.   unsigned int x;
  31.   unsigned int i_old;
  32.   IO_STATUS stat = IN_NOK;
  33.  
  34.   i_alt = *i = 0;
  35.   while (isdigit((c = getchar())) != 0)
  36.   {
  37.     x = (unsigned int) c - 48;    /* 48 is ASCII 0 */
  38.     *i = *i * 10 + x;
  39.     
  40.     if (*i <= i_old)  
  41.     {
  42.       puts("too big!"); 
  43.       return IN_NOK;
  44.     }
  45.     i_old = *i; 
  46.     stat = IN_OK;
  47.   }
  48.  
  49.  return OK;
  50. }
  51.  
  52.  
  53.